package project.base.common.convert

import com.alibaba.fastjson.JSONArray
import org.apache.ibatis.type.BaseTypeHandler
import org.apache.ibatis.type.JdbcType
import org.apache.ibatis.type.MappedJdbcTypes
import org.apache.ibatis.type.MappedTypes
import java.sql.CallableStatement
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.sql.SQLException

/**
 * MyBatis Array类型处理器
 * @author: 三味
 * @update: 2022/3/3 15:39
 */
@MappedTypes(JSONArray::class)
@MappedJdbcTypes(JdbcType.VARCHAR)
class ArrayJsonHandler : BaseTypeHandler<JSONArray>() {
    //设置非空参数
    @Throws(SQLException::class)
    override fun setNonNullParameter(ps: PreparedStatement, i: Int, parameter: JSONArray, jdbcType: JdbcType?) {
        ps.setString(i, parameter.toJSONString().toString())
    }

    //根据列名，获取可以为空的结果
    @Throws(SQLException::class)
    override fun getNullableResult(rs: ResultSet, columnName: String?): JSONArray? {
        val sqlJson = rs.getString(columnName)
        return if (null != sqlJson) {
            JSONArray.parseArray(sqlJson)
        } else null
    }

    //根据列索引，获取可以为空的结果
    @Throws(SQLException::class)
    override fun getNullableResult(rs: ResultSet, columnIndex: Int): JSONArray? {
        val sqlJson = rs.getString(columnIndex)
        return if (null != sqlJson) {
            JSONArray.parseArray(sqlJson)
        } else null
    }

    @Throws(SQLException::class)
    override fun getNullableResult(cs: CallableStatement, columnIndex: Int): JSONArray? {
        val sqlJson = cs.getString(columnIndex)
        return if (null != sqlJson) {
            JSONArray.parseArray(sqlJson)
        } else null
    }
}
